package com.webshop.servlet;

import com.webshop.Dao.UserDao;
import com.webshop.domain.user.User;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookie = req.getCookies();
        HttpSession session = req.getSession();
        session.setMaxInactiveInterval(-1);
        String username = null;
        String password = null;
        User user = null;



        for(Cookie c: cookie){
            if (c.getName().equals("username"))
                username = c.getDomain();
            if (c.getName().equals("password"))
                password = c.getDomain();
            if(username!=null&&password!=null){
                System.out.println("cookie ok");
                user = UserDao.getUser(username,password);
                if(user==null){
                    resp.sendRedirect("login.jsp");
                    return;
                }else {
                    session.setAttribute("user",user);
                    resp.sendRedirect("index.jsp");
                    return;
                }
            }
        }
        username = req.getParameter("username");
        password = req.getParameter("password");
        if(username==null||password==null){
            resp.sendRedirect("login.jsp");
            return;
        }
        user = UserDao.getUser(username,password);
        if(user==null){
            resp.sendRedirect("erroruser.jsp");
            return;
        }
        session.setAttribute("user",user);
        resp.sendRedirect("index.jsp");
        return;
    }
}
